package com.tjetc.dao;

import com.tjetc.domain.Player;
import com.tjetc.utils.Db;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class PlayerDao {
    private QueryRunner runner=new QueryRunner();
    public List<Player> showPlayerSalary() throws SQLException {
       return   Db.runner.query("select name,salary from player",new BeanListHandler<>(Player.class));
    }

    public Player findByPlayerName(String playerName) throws SQLException {
        return Db.runner.query("select * from player where name=?",new BeanHandler<>(Player.class),playerName);
    }


    public void update(int playerid, String playerName1, int playerAge, int playerHeight, int playerWeight, int position, int team_id, int playerSalary, int likes,String playerName) throws SQLException {
        runner.update(Db.getConnection(),"update player set id=?,name =?,age=?,height=?,weight=?,position =?,team_id=?,salary=?,likes=? where name =?",playerid,playerName1,playerAge,playerHeight,playerWeight,position,team_id,playerSalary,likes,playerName);
    }

 private int getCurrentLikes(String playerName) throws SQLException {
     QueryRunner runner = new QueryRunner();
     Object  result = runner.query(Db.getConnection(),"select likes from player where name = ?", new ScalarHandler<>(), playerName);
     if (result == null) {
         return 0;
     } else {
         Long likesLong = (Long) result;
         return likesLong.intValue();
     }
 }

    public void Likes(String playerName) throws SQLException {
        int currentLikes = getCurrentLikes(playerName);
        int newLikes = currentLikes + 10;
        runner.update(Db.getConnection(), "update player set likes=? where name =?", newLikes, playerName);
    }

    public Player findByPlayerId(int playerId) throws SQLException {
        return Db.runner.query("select * from player where id=?",new BeanHandler<>(Player.class),playerId);
    }

    public List<Player> findPlayer() throws SQLException {
        return Db.runner.query("select * from player",new BeanListHandler<>(Player.class));
    }
}
